import sys
import cv2
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from page.ui_demo import Ui_MainWindow


class DemoEntry(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.camera = cv2.VideoCapture(0)
        self.is_cam_opened = False

        self.__timer = QTimer(self)
        self.__timer.timeout.connect(self.__queryFrame)
        self.__timer.setInterval(30)

    def btnOpenCamera_Click(self):
        self.is_cam_opened = ~ self.is_cam_opened
        if self.is_cam_opened:
            self.btnOpenCamera.setText("关闭摄像头")
            self.__timer.start()
        else:
            self.btnOpenCamera.setText("打开摄像头")
            self.__timer.stop()

    def btnCapture_Click(self):

        if not self.is_cam_opened:
            return

        self.captured = self.frame
        self.picture()

    def btnReadImage_Click(self):
        filename, _ = QFileDialog.getOpenFileName(self, '打开图片')
        if filename:
            self.captured = cv2.imread(str(filename))
            self.captured = cv2.cvtColor(self.captured, cv2.COLOR_BGR2RGB)
            self.picture()

    def btnGray_Click(self):
        if not hasattr(self, "captured"):
            return
        self.captured = cv2.cvtColor(self.captured, cv2.COLOR_BGR2GRAY)
        self.pictures()

    def btnThreshold_Click(self):

        if not hasattr(self, 'captured'):
            return
        _, self.captured = cv2.threshold(self.captured, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        self.pictures()

    def picture(self):
        rows, cols, channels = self.captured.shape
        bytesPerLine = channels * cols
        QImg = QImage(self.captured.data, cols, rows, bytesPerLine, QImage.Format_RGB888)
        self.labelCapture.setPixmap(
            QPixmap.fromImage(QImg).scaled(self.labelCapture.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))

    def pictures(self):
        rows, columns = self.captured.shape
        bytesPerLine = columns
        QImg = QImage(self.captured.data, columns, rows, bytesPerLine, QImage.Format_Indexed8)
        self.labelResult.setPixmap(
            QPixmap.fromImage(QImg).scaled(self.labelResult.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))

    def __queryFrame(self):

        ret, self.frame = self.camera.read()
        img_rows, img_cols, channels = self.frame.shape
        bytesPerLine = channels * img_cols
        cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB, self.frame)
        QImg = QImage(self.frame.data, img_cols, img_rows, bytesPerLine, QImage.Format_RGB888)
        self.labelCamera.setPixmap(
            QPixmap.fromImage(QImg).scaled(self.labelCamera.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = DemoEntry()
    win.show()
    sys.exit(app.exec_())
